package com.changeover.gwt.login.client;

import com.changeover.gwt.login.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Login implements EntryPoint {
    /**
     * The message displayed to the user when the server cannot be reached or
     * returns an error.
     */
    private static final String SERVER_ERROR = "An error occurred while "
        + "attempting to contact the server. Please check your network " + "connection and try again.";

    /**
     * Create a remote service proxy to talk to the server-side Greeting service.
     */
    private final ILoginServiceAsync loginService = GWT.create(ILoginService.class);
//    private final IAuthenticationServiceAsync authService = GWT.create(IAuthenticationService.class);

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
        final Label errorLabel = new Label();

        // Add the nameField and sendButton to the RootPanel
        // Use RootPanel.get() to get the entire body element
        RootPanel.get("labelError").add(errorLabel);
        
        Label lblLoginForm = new Label("Login form:");
        RootPanel.get("formLoginTitle").add(lblLoginForm);
        lblLoginForm.setWidth("");
        lblLoginForm.setStyleName("h2");
        
        Label lblLogin = new Label("Login:");
        RootPanel.get("labelLogin").add(lblLogin);
        lblLogin.setWidth("80px");
        final TextBox loginField = new TextBox();
        RootPanel.get("fieldLogin").add(loginField);
        loginField.setSize("163px", "16px");
        
        // Focus the cursor on the name field when the app loads
        loginField.setFocus(true);
        
        Label lblPassword = new Label("Password:");
        RootPanel.get("labelPassword").add(lblPassword);
        lblPassword.setSize("80px", "");
        final PasswordTextBox passwordTextBox = new PasswordTextBox();
        RootPanel.get("fieldPassword").add(passwordTextBox);
        passwordTextBox.setSize("163px", "16px");
        
        final Button loginButton = new Button("login");
        loginButton.setStyleName("loginButton");
        RootPanel.get("buttonLogin").add(loginButton);
        
        // We can add style names to widgets
        loginButton.addStyleName("sendButton");
        loginField.selectAll();

        // Create the popup dialog box
        final DialogBox dialogBox = new DialogBox();
        dialogBox.setText("Remote Procedure Call");
        dialogBox.setAnimationEnabled(true);
        final Button closeButton = new Button("Close");
        // We can set the id of a widget by accessing its Element
        closeButton.getElement().setId("closeButton");
        final Label textToServerLabel = new Label();
        final HTML serverResponseLabel = new HTML();
        VerticalPanel dialogVPanel = new VerticalPanel();
        dialogVPanel.addStyleName("dialogVPanel");
        dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
        dialogVPanel.add(textToServerLabel);
        dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
        dialogVPanel.add(serverResponseLabel);
        dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
        dialogVPanel.add(closeButton);
        dialogBox.setWidget(dialogVPanel);

        // Add a handler to close the DialogBox
        closeButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                dialogBox.hide();
                loginButton.setEnabled(true);
                loginButton.setFocus(true);
            }
        });

        // Create a handler for the sendButton and nameField
        class LoginHandler implements ClickHandler, KeyUpHandler {
            /**
             * Fired when the user clicks on the sendButton.
             */
            public void onClick(ClickEvent event) {
                sendNameToServer();
            }

            /**
             * Fired when the user types in the nameField.
             */
            public void onKeyUp(KeyUpEvent event) {
                errorLabel.setText("");
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    sendNameToServer();
                }
            }

            /**
             * Send the name from the nameField to the server and wait for a response.
             */
            private void sendNameToServer() {
                // First, we validate the input.
                errorLabel.setText("");
                String login = loginField.getText();
                if (!FieldVerifier.isValidLogin(login)) {
                    errorLabel.setText("Please enter at least four characters in to login field");
                    return;
                }
                String password = passwordTextBox.getText();
                if (!FieldVerifier.isValidPassword(password)) {
                    errorLabel.setText("Please enter at least six characters in to password");
                    return;
                }

                // Then, we send the input to the server.
                loginButton.setEnabled(false);
                textToServerLabel.setText(login);
                serverResponseLabel.setText("");
                loginService.login(login, password, new AsyncCallback<String>() {
                    public void onFailure(Throwable caught) {
                        // Show the RPC error message to the user
                        dialogBox.setText("Remote Procedure Call - Failure");
                        serverResponseLabel.addStyleName("serverResponseLabelError");
                        serverResponseLabel.setHTML(SERVER_ERROR);
                        dialogBox.center();
                        closeButton.setFocus(true);
                    }

                    public void onSuccess(String result) {
                        dialogBox.setText("Remote Procedure Call");
                        serverResponseLabel.removeStyleName("serverResponseLabelError");
                        serverResponseLabel.setHTML(result);
                        dialogBox.center();
                        closeButton.setFocus(true);
                    }
                });
            }
        }

        // Add a handler to send the name to the server
        LoginHandler handler = new LoginHandler();
        loginButton.addClickHandler(handler);
        loginField.addKeyUpHandler(handler);
        
//        // Security
//        authService.retrieveUsername(new AsyncCallback<String>() {
//            public void onFailure(Throwable caught) {
//                dialogBox.setText("Remote Procedure Call - Failure");
//            }
//
//            public void onSuccess(String result) {
//                dialogBox.add(new Label("Success!"));
//            }
//        });
    }
}
